import { _decorator, Component, Node, instantiate, Prefab, BoxCollider, ITriggerEvent } from 'cc';
import { constant } from '../constant';
import { gameManeger } from '../framework/gameManeger';
import { PoolManager } from '../framework/PoolManager';
const { ccclass, property } = _decorator;
const OUTOFSCREEN = 50;//销毁距离
@ccclass('enemyplane01')
export class enemyplane extends Component {
    @property public createBullTime = 0.8;//子弹发射周期
    public enemySpeed = 0;

    private _curBulletTime = 0;
    private _needBullet = false;
    private _gameManeger: gameManeger = null;


    onEnable() {
        const collider = this.getComponent(BoxCollider);
        collider.on("onTriggerEnter", this._onTriggerEnter, this);
    }
    onDisEnable() {
        const collider = this.getComponent(BoxCollider);
        collider.off("onTriggerEnter", this._onTriggerEnter, this);
    }
    start() {

    }

    update(deltaTime: number) {
        const pos = this.node.position;
        const movDistance = pos.z + this.enemySpeed;
        this.node.setPosition(pos.x, pos.y, movDistance);
        //是否需要发射子弹
        if (this._needBullet) {
            this._curBulletTime += deltaTime;
            if (this._curBulletTime > this.createBullTime) {
                this._curBulletTime = 0;
                this._gameManeger.createEnemyBullet(this.node.position);
            }
        }

        if (movDistance > OUTOFSCREEN) {
            PoolManager.instance().putNode(this.node);
            //this.node.destroy();
            //console.log("dijiyijingchujie");
        }
    }
    //敌机发射子弹 
    // public createEnemyBullet() {
    //     const bullet = instantiate(this.bullet02);//实例化子弹
    //     bullet.setParent(this.bulletRoot);//设置子弹父节点
    //     bullet.setPosition(0, 0, 5);//setpositon相对父节点的位置,默认应该时父节点位置
    //     const bulletComp = bullet.getComponent(Bullet);//获取子弹节点得脚本组件
    //     bulletComp.show(0.8, true, constant.Direction.MID);//传递实例化子弹所需要的参数
    //     const colliderComp = bullet.getComponent(BoxCollider);
    //     colliderComp.setGroup(constant.CollisionType.ENEMY_BULLET);
    //     colliderComp.setMask(constant.CollisionType.PLANE);
    // }
    //响应触发函数
    private _onTriggerEnter(event: ITriggerEvent) {
        const group = event.otherCollider.getGroup();
        if (group == constant.CollisionType.PLANE || group == constant.CollisionType.PLAYER_BULLET) {
            this._gameManeger.addScore();
            this._gameManeger.createEffect(this.node.position);
            PoolManager.instance().putNode(this.node);
            //this.node.destroy();
        }
    }
    //笔记：show函数一般用于初始化实例时传递参数
    show(_gameManeger: gameManeger, speed: number, _needBullet: boolean) {//为飞机设置速度
        this.enemySpeed = speed;
        this._needBullet = _needBullet;
        this._gameManeger = _gameManeger;
    }
}

